﻿using System;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using TheGameClient.Processes;
using TheGameClient.Webservices;

namespace TheGameClient
{
	public partial class FeatureMarketControl : ISystemFeature
	{
		public FeatureMarketControl()
		{
			// Required to initialize variables
			InitializeComponent();
			ProcessId = Guid.NewGuid();
		}

		#region ISystemFeature Members

		public Guid ProcessId { get; private set; }

		public string ProcessName
		{
			get { return "Market"; }
		}

		public ulong InterfaceId
		{
			get { return new Guid("{712EB328-67BE-4C5C-A5FC-24B50EFB0A1C}").ToLong(); }
		}

		public InterfaceCategory Category
		{
			get { return InterfaceCategory.SystemFeature; }
		}

		public ulong SystemId { get; private set; }

		public void Load(ulong systemId)
		{
			SystemId = systemId;
			App.Client.GetAvailableFundsCompleted += ClientGetAvailableFundsCompleted;
			App.Client.GetAvailableFundsAsync(App.InternalSessionId, systemId);
			App.Client.GetAvailableHardwareCompleted += ClientGetAvailableHardwareCompleted;
			App.Client.GetAvailableHardwareAsync(App.InternalSessionId, SystemId);
			App.Client.GetAvailableSoftwareCompleted += ClientGetAvailableSoftwareCompleted;
			App.Client.GetAvailableSoftwareAsync(App.InternalSessionId, SystemId);
		}

		#endregion

		#region funds

		private void ClientGetAvailableFundsCompleted(object sender, GetAvailableFundsCompletedEventArgs e)
		{
			App.Client.GetAvailableFundsCompleted -= ClientGetAvailableFundsCompleted;
			if (e.Error != null)
			{
				App.ServerError();
				return;
			}
			lblTotalCredits.Text = string.Format("{0:### ### ### ### ### ###.##}", e.Result).Trim();
			lblTotalCredits2.Text = string.Format("{0:### ### ### ### ### ###.##}", e.Result).Trim();
		}

		#endregion

		#region software

		private void TabSoftwareMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
		}

		private void ClientGetAvailableSoftwareCompleted(object sender, GetAvailableSoftwareCompletedEventArgs e)
		{
			App.Client.GetAvailableSoftwareCompleted -= ClientGetAvailableSoftwareCompleted;
			if (e.Error != null)
			{
				App.ServerError();
				return;
			}
			if (e.Result != null)
				dgrdSoftware.ItemsSource = e.Result.ToList();
		}

		#endregion

		#region Hardware

		private PagedCollectionView _pcv;

		private void TabHardwareMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
		}

		private void ClientGetAvailableHardwareCompleted(object sender, GetAvailableHardwareCompletedEventArgs e)
		{
			App.Client.GetAvailableHardwareCompleted -= ClientGetAvailableHardwareCompleted;
			if (e.Error != null)
			{
				App.ServerError();
				return;
			}
			if (e.Result != null)
			{
				_pcv = new PagedCollectionView(e.Result.ToList());
				PropertyGroupDescription pcd = new PropertyGroupDescription("ItemType", new CategoryNameConverter());
				_pcv.GroupDescriptions.Add(pcd);
				dgrdHardware.ItemsSource = _pcv;
			}
		}

		private void DgrdHardwareSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			MarketItem item = dgrdHardware.SelectedItem as MarketItem;
			if (item != null)
				txtDescription.Text = item.Description;
		}

		#endregion

		private void BtnBuyHardwareClick(object sender, RoutedEventArgs e)
		{
			if (dgrdHardware.SelectedItem is MarketItem)
			{
				MarketItem mi = dgrdHardware.SelectedItem as MarketItem;
				App.Client.PurchaseHardwareCompleted += ClientPurchaseHardwareCompleted;
				App.Client.PurchaseHardwareAsync(App.InternalSessionId, SystemId, mi.ItemId);
				btnBuyHardware.IsEnabled = false;
			}
		}

		private void ClientPurchaseHardwareCompleted(object sender, PurchaseHardwareCompletedEventArgs e)
		{
			btnBuyHardware.IsEnabled = true;
			App.Client.PurchaseHardwareCompleted -= ClientPurchaseHardwareCompleted;
			if (e.Error != null)
			{
				App.ServerError();
				return;
			}
			if (!e.Result)
				MessageBox.Show("The item you selected could not be purchased. Check your funds.");
			else
			{
				App.Client.GetAvailableFundsCompleted += ClientGetAvailableFundsCompleted;
				App.Client.GetAvailableFundsAsync(App.InternalSessionId, SystemId);
			}
		}

		private void BtnBuySoftwareClick(object sender, RoutedEventArgs e)
		{
			if (dgrdSoftware.SelectedItem is MarketItem)
			{
				MarketItem mi = dgrdSoftware.SelectedItem as MarketItem;
				App.Client.PurchaseProgramCompleted += ClientPurchaseProgramCompleted;
				App.Client.PurchaseProgramAsync(App.InternalSessionId, SystemId, mi.ItemId);
				btnBuySoftware.IsEnabled = false;
			}
		}

		private void ClientPurchaseProgramCompleted(object sender, PurchaseProgramCompletedEventArgs e)
		{
			btnBuySoftware.IsEnabled = true;
			App.Client.PurchaseProgramCompleted -= ClientPurchaseProgramCompleted;
			if (e.Error != null)
			{
				App.ServerError();
				return;
			}
			if (!e.Result)
				MessageBox.Show("The item you selected could not be purchased. Check your funds and available memory!");
			else
			{
				App.Client.GetAvailableFundsCompleted += ClientGetAvailableFundsCompleted;
				App.Client.GetAvailableFundsAsync(App.InternalSessionId, SystemId);
			}
		}
	}

	public class FeatureMarketUiFactory : UiFactoryBase
	{
		public override InterfaceCategory UiCategory
		{
			get { return InterfaceCategory.SystemFeature; }
		}

		public override IProcess CreateProgram()
		{
			return new FeatureMarketControl();
		}
	}

	public class CategoryNameConverter : IValueConverter
	{
		#region IValueConverter Members

		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (value is MarketItemType)
			{
				switch ((MarketItemType) value)
				{
				case MarketItemType.Blueprint:
					return "Blueprints";
				case MarketItemType.Cpu:
					return "CPUs";
				case MarketItemType.Memory:
					return "Memory";
				case MarketItemType.Nic:
					return "Network adapters";
				default:
					return value;
				}
			}
			return value;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}

		#endregion
	}
}